package com.zgs.mall.auth.web;

import com.alibaba.fastjson.TypeReference;
import com.zgs.common.utils.R;
import com.zgs.mall.auth.feign.LoginService;
import com.zgs.mall.auth.feign.RegistUserService;
import com.zgs.mall.auth.feign.ThirdPartFeignService;
import com.zgs.mall.auth.vo.MemberRespVo;
import com.zgs.mall.auth.vo.UserLoginVo;
import com.zgs.mall.auth.vo.UserRegisVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisAccessor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RegistUserService registUserService;
    @ResponseBody
    @GetMapping("/sms/sendCode")
    public  R sendCode(String phone){
        String s = stringRedisTemplate.opsForValue().get("sms:code:" + phone);
       if (!StringUtils.isEmpty(s)){
           long l = Long.parseLong(s.split("_")[1]);
           if (System.currentTimeMillis()-l<60000){
               //60秒内不能再发
               return R.error();
           }
       }
        //验证码时间戳
        String string = UUID.randomUUID().toString()+"_"+System.currentTimeMillis();

        //验证码的再次校验 redis存key-phone value-code
        stringRedisTemplate.opsForValue().set("sms:code:"+phone,string,60*5, TimeUnit.SECONDS);
        return  R.ok();
    }
    @PostMapping("regist")
    public  String  rerUser(@Valid UserRegisVo userRegisVo,
                            BindingResult result,
                            RedirectAttributes redirectAttributes){
        if (result.hasErrors()){
            Map<String, Object> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getRejectedValue));
            redirectAttributes.addFlashAttribute("error",collect);
            return "redirect:http://auth.mall.com/reg.html";
        }
        String code = userRegisVo.getCode();
        //校验验证码
        String phone = userRegisVo.getPhone();
        String s = stringRedisTemplate.opsForValue().get("sms:code:" + phone);
        if(StringUtils.isEmpty(s)){
            Map<String, Object> collect = new HashMap<>();
            collect.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("error",collect);
            return "redirect:http://auth.mall.com/reg.html";
        }
        String[] s1 = s.split("_");
        if (code.equals(s1[1])){
            //验证码验证成功
            stringRedisTemplate.delete("sms:code:" + phone);
            //调用远程接口 进行注册
            registUserService.regist(userRegisVo);
            return "redirect:/login.html";
        }else{
            Map<String, Object> collect = new HashMap<>();
            collect.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("error",collect);
            return "redirect:http://auth.mall.com/reg.html";
        }
    }
    @Autowired
    LoginService loginService;
    //账号密码登录
    @PostMapping("/login")
    public String login(UserLoginVo vo,RedirectAttributes redirectAttributes,HttpSession session){
        R login = loginService.login(vo);
        Integer code = login.getCode();
        if (code !=0){
            String msg = login.get("msg").toString();
            Map map =new HashMap();
            map.put("msg",msg);
            redirectAttributes.addFlashAttribute("error",map);
            return "redirect:http://auth.mall.com/login.html";
        }
        Object data = login.get("data");
        session.setAttribute("user_data",data);
        return "redirect:http://mall.com";
    }
    //社交登录
    public void oauthlogin(String code, HttpServletResponse servletResponse,HttpSession session){
        //code 换取accessToken
        //accessToken 获取用户信息 第一次登录 先注册到用户账号表
        //登录成功 -session共享问题 同域名- nginx hash算法  redis管理session
        //不同域名-子域名
        /**
         * 第一次使用session：命令浏览器保存卡号 JESSIONID 这个cookie
         * 以后浏览器访问哪个网站就会带上这个网站的 cookie
         * 子域名 mall.com  auth.mall.com
         * 发卡的时候（指定域名为父域名），即使是子系统发的卡（cookie）也能让父域名直接使用
         */
        //将登录的用户放到session
        session.setAttribute("user_data","");//springsersion 来解决
//        Cookie cookie = new Cookie("JESSIONID", "");
//        cookie.setDomain(".mall.com");
//        servletResponse.addCookie(cookie);
    }
}
